package org.wzy.springcloud.feign.decoder;

import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.FeignException;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.wzy.springcloud.feign.config.FeignConfig;

/**
 * {@link ErrorDecoder} 配置类
 * <p>业务中出现的异常并非全部为服务提供者的异常，有可能是404/400...等
 * <p>因此在进行feign client调用的时候，需要进行errorDecoder处理，适配为HystrixBadRequestException，好避开circuit breaker的统计，否则就容易误判
 * <p>不能因为缺少页面/REST URL或者缺少参数而熔断整个服务，因此需要过滤掉这部分异常。
 *
 * @author wzy_h
 * @version 1.0
 * @date 23:30 2017/11/24
 */
public class BizErrorDecoder implements ErrorDecoder {
    private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(FeignConfig.class);
    private static final int STATUS_START = 400;
    private static final int STATUS_END = 499;

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() >= STATUS_START && response.status() <= STATUS_END) {
            LOGGER.error("<=== Feign Client 出现异常, type={}", response);
            return new HystrixBadRequestException("Feign Client 出现非熔断性异常，请检查业务代码...methodKey=" + methodKey + ", response=" + response);
        }
        return FeignException.errorStatus(methodKey, response);
    }
}
